/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using CookComputing.XmlRpc;

namespace Whitemice.ZOGI
{
  public partial class Task : Entity, IZOGIStorable
  {
    protected MultiResultCallback  receiveData = null;
    
    public Task() : base()
    {
      CreatorId = Server.Connection.UserId;
      SetEntityName("Task");
      SetVersion(0);
      Start = DateTime.Now;
      End = Start.AddDays(7.0);
      SetExecutor(CreatorId);
    }
          
    public Task(IDictionary<string,object> x, int d)
      : base(x, d)
    {
    }
    
    internal override void Take(IDictionary<string,object> x, int d)
    {
      base.Take(x, d);
		  AccountingInfo = AsString(x, "accountingInfo");
		  ActualWork = AsInt32(x ,"actualWork");
			AssociatedCompanies = AsString(x, "associatedCompanies");
			AssociatedContacts = AsString(x, "associatedContacts");
			Category = AsString(x, "category");
			Comment = AsString(x, "comment");
			CreatorId = AsInt32(x, "creatorObjectId");
			End = AsDateTime(x, "end");
			SetExecutor(AsInt32(x, "executantObjectId"));
			Keywords = AsString(x, "keywords");
			Kilometers = AsInt32(x, "kilometers");
		  SetPriority(AsInt32(x, "priority"));
			Kind = AsString(x, "kind");
			Name = AsString(x, "name");
			SetStatus(AsString(x, "status"));
			SetNotification(AsInt32(x, "notify"));
			PercentComplete = AsInt32(x, "percentComplete");
			SetProjectId(AsInt32(x, "objectProjectId"));				
			SetSensitivity(AsInt32(x, "sensitivity"));
			Start = AsDateTime(x, "start");
			TotalWork = AsInt32(x, "totalWork");
      SetCompletionDate(AsDateTime(x, "completionDate"));
    }
    
    protected void RequestCreator()
    {
      FetchCommand command;

      if (receiveData == null)
        receiveData = new MultiResultCallback(ReceiveData);
      command = new FetchCommand(new int[] { CreatorId }, 65535, "MyCreator");
      command.Callback = receiveData;
      Server.Connection.RunCommand(command, RpcPriority.Background);
    }

    protected void RequestExecutor()
    {
      FetchCommand command;

      if (receiveData == null)
        receiveData = new MultiResultCallback(ReceiveData);
      command = new FetchCommand(new int[] { ExecutorId }, 65535, "MyExecutor");
      command.Callback = receiveData;
      Server.Connection.RunCommand(command, RpcPriority.Background);
    }

    protected void RequestProject()
    {
      FetchCommand command;

      if (receiveData == null)
        receiveData = new MultiResultCallback(ReceiveData);
      command = new FetchCommand(new int[] { ParentObjectId }, 0, "MyProject");
      command.Callback = receiveData;
      Server.Connection.RunCommand(command, RpcPriority.Background);
    }    

    protected void ReceiveData(object sender, RPCEventArgs args)
		{
			string my = (args.Context.ToString());
		  if (args.HasResults)
			{
        switch(my)
        {
          case "MyCreator": SetCreator(args.Payload.First()); break;
          case "MyExecutor": SetExecutor(args.Payload.First()); break;
          case "MyProject":
            var entity = args.Payload.First();
            if (entity is Whitemice.ZOGI.Project)
              if (entity.ObjectId == ParentObjectId)
                this._project = (entity as Whitemice.ZOGI.Project);
            break;
        }
			}
		} // end ReceiveCreator

    public void GetHistory(MultiResultCallback _callback, object context)
    {
      FetchCommand command = new FetchCommand(ObjectId, 65535, context);
      command.Callback = _callback;
      Server.Connection.RunCommand(command);
    }
    
    public override bool FirstClass { get { return true; } }
    
    public string AccountingInfo { get; set; }
		public int ActualWork { get; set; }
		public string	AssociatedCompanies  { get; set; }
		public string	AssociatedContacts { get; set; }
		public string	Category { get; set; }
		public string	Comment { get; set; }
    
    protected int     _creatorId = 0;
    protected Contact _creator = null;
    protected void SetCreator(Entity e) 
    {
      if (e is Whitemice.ZOGI.Contact)
        _creator = (e as Contact);
        else _creator = null;
    }
		public int CreatorId  
    { 
      get { return _creatorId; }
      set
      {
        if (value != _creatorId)
        {
          _creatorId = value;
          RequestCreator();
        }
      }
    }
		public Contact Creator
		{
		  get 
		  { 
		    return Server.Cache.Get<Whitemice.ZOGI.Contact>(CreatorId); 
		  }
		}
    public string CreatorName
    {
      get
      {
        if (_creator == null)
          return string.Empty;
        return string.Format("{0}, {1}", _creator.LastName, _creator.FirstName);
      }
    }
		
		public DateTime	End  { get; set; }

    protected int _executorId = 0;
    protected Entity _executor = null;
    protected void SetExecutor(int id)
    {
      if (id != _executorId)
      {
        _executorId = id;
        RequestExecutor();
      }
    }
    protected void SetExecutor(Entity e) { _executor = e; }
    public int ExecutorId  
    { 
      get { return _executorId; }
      set { SetExecutor(value); }
    }
		public Entity Executor
		{
		  get { return _executor; }
		}
    public string ExecutorName
    {
      get
      {
        if (Executor == null)
          return string.Empty;
        if (Executor is Team)
          return (Executor as Team).Name;
        if (Executor is Contact)
          return string.Format("{0}, {1}", (Executor as Contact).LastName,
                                           (Executor as Contact).FirstName);
        return "Unknown";
      }
    }
		
		public string	Keywords  { get; set; }
		public int	Kilometers  { get; set; }
		
		protected int _priority;
		protected void SetPriority(int p) { _priority = p; }
		protected int GetPriority() { return _priority; }
		public TaskPriority Priority
		{
 			get 
 			{ 
				switch (_priority)
				{
					case 0: return TaskPriority.VeryHigh;
					case 1: return TaskPriority.High;
					case 3: return TaskPriority.Low;
					case 4: return TaskPriority.VeryLow;
					default: return TaskPriority.Average;
				} 			
 			}
 			set { _priority = Convert.ToInt32(value); }
		}
		
		public string	Kind  { get; set; }
		public string	Name  { get; set; }
		
		protected string _status;
		protected void SetStatus(string s) { _status = s; }
		public TaskStatus Status
		{
 			get { return Task.StringToStatus(_status); }
 			set { SetStatus(Task.StatusToString(value)); }
 	  }
		
		protected int _notify;
		protected void SetNotification(int n) { _notify = n; }
		protected int GetNotification() { return _notify; }
		public TaskNotification Notification
		{
 			get 
 			{
				switch(_notify)
				{
					case 1: return TaskNotification.Always;
					case 2: return TaskNotification.AcceptDone;
					default: return TaskNotification.Never;
				}
 			} 
 			set 
 			{ 
 				switch(value)
 				{
 					case TaskNotification.Always: SetNotification(1); break;
 					case TaskNotification.AcceptDone: SetNotification(2); break;
 					default: SetNotification(0); break;
 				}
 			} 
		}
		
		public int PercentComplete  { get; set; }
		
	  public int ProjectId 
	  { 
	    get { return ParentObjectId; }
	    set { SetProjectId(value); }
	  }

    protected Project _project;
    protected void SetProjectId(int projectId)
    {
      SetParentObjectId(projectId);
      if (ParentObjectId == 0)
        _project = null;
      else RequestProject();
    }
	  public Project Project 
	  { 
	    get { return  _project; }
	  }
    public string ProjectName
    {
      get
      {
        if (Project == null)
          return string.Empty;
        return Project.Name;
      }
    }
	  
	  protected int _sensitivity;
	  protected void SetSensitivity(int s) { _sensitivity = s; }
	  protected int GetSensitivity() { return _sensitivity; }
		public TaskSensitivity Sensitivity  
		{ 
 			get { return Task.IntToSensitivity(GetSensitivity()); }
 			set { SetSensitivity(Task.SensitivityToInt(value)); }
		}

    protected DateTime? _complete;
    protected void SetCompletionDate(DateTime? d) { _complete = d; }
    public DateTime? CompletionDate { get { return _complete; } }
    
		public DateTime	Start  { get; set; }
	  public int TotalWork { get; set; }
	  
	  public IEnumerable<TaskNotation> Notations
    {
      get { return Server.Cache.GetChildrenOf<TaskNotation>(ObjectId); }
    }
	  
		public override XmlRpcStruct Encode() 
		{
			XmlRpcStruct	rpcStruct;
			
			rpcStruct = base.Encode();

			rpcStruct = new XmlRpcStruct();
			rpcStruct.Add("keywords", Keywords);
			rpcStruct.Add("end", End);
    	if (ObjectId < 0)
    	{
    		rpcStruct.Add("objectId", 0);
    		rpcStruct.Add("comment", Comment);
    	} else rpcStruct.Add("objectId", ObjectId);
			rpcStruct.Add("priority", GetPriority());
			rpcStruct.Add("sensitivity", GetSensitivity());
			rpcStruct.Add("percentComplete", PercentComplete);
			rpcStruct.Add("start", Start);
			rpcStruct.Add("kilometers", Kilometers.ToString());
			rpcStruct.Add("totalWork", TotalWork);
			rpcStruct.Add("kind", Kind);
			rpcStruct.Add("actualWork", ActualWork);
      rpcStruct.Add("notify", GetNotification());
			rpcStruct.Add("objectProjectId", ProjectId);
			rpcStruct.Add("name", Name);
			rpcStruct.Add("entityName", "Task");
			rpcStruct.Add("executantObjectId", ExecutorId);
			rpcStruct.Add("accountingInfo", AccountingInfo);
			return rpcStruct;
	  }
  }
}
